package com.aids_malaria.ui;

import android.Manifest;
import android.content.Intent;
import android.os.Handler;
import android.support.annotation.NonNull;

import com.aids_malaria.R;
import com.aids_malaria.app.Constant;
import com.aids_malaria.base.BaseActivity;
import com.aids_malaria.db.DBManager;
import com.aids_malaria.http.RetrofitFactory;
import com.aids_malaria.http.RxScheduler;
import com.aids_malaria.http.api.RetrofitApi;
import com.aids_malaria.http.response.DoLoginResponse;
import com.aids_malaria.http.response.login.LoginObserver;
import com.aids_malaria.util.AppUtil;
import com.aids_malaria.util.SpUtil;
import com.aids_malaria.util.ToastUtil;

import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class WelcomeActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks{

    String PERMISSION_STORAGE_MSG = "请授予权限，否则影响部分使用功能";
    int PERMISSION_STORAGE_CODE = 10001;

    String[] PERMS = {Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CALL_PHONE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.READ_PHONE_STATE};

    @Override
    protected int getLayoutId() {
        return R.layout.activity_welcome;
    }

    @Override
    protected void initView() {
        super.initView();
        requestPermission();
    }

    private void requestPermission(){
        if (EasyPermissions.hasPermissions(this, PERMS)) {
            // 已经申请过权限，做想做的事
            goToLogin();
        } else {
            // 没有申请过权限，现在去申请
            /**
             *@param host Context对象
             *@param rationale  权限弹窗上的提示语。
             *@param requestCode 请求权限的唯一标识码
             *@param perms 一系列权限
             */
            EasyPermissions.requestPermissions(this, getString(R.string.qx_get), PERMISSION_STORAGE_CODE, PERMS);
        }
    }

    @Override
    public void checkLink() {
        //欢迎页不请求网络连接状态
    }

    private void goToLogin(){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                boolean isLogin = SpUtil.getBoolean(mContext, Constant.IS_LOGIN,false);
                if(isLogin){
                    String userCode = SpUtil.getString(mContext, Constant.USER_ACCOUNT, "");
                    String password = SpUtil.getString(mContext, Constant.USER_PASSWORD, "");
//                    String deviceId = AppUtil.getDeviceId(mContext);
                    String deviceId = AppUtil.getDeviceId(mContext);
                    //TODO 更新最新权限数据
//                    doLogin(userCode,deviceId,password);
                    startActivity(MainActivity.class);
                    finish();
                }else{
                    startActivity(LoginActivity.class);
                    finish();
                }
            }
        },1000);
    }

    /**
     * 登录
     *
     * @param userCode
     * @param padId
     * @param password
     */
    private void doLogin(String userCode, String padId, String password) {
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).dologin(userCode, padId, password)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new LoginObserver<DoLoginResponse>() {

                    @Override
                    protected void onStart() {

                    }

                    @Override
                    protected void onSuccess(DoLoginResponse data) throws Exception {
                        //保存是否记住账号
                        SpUtil.getBoolean(mContext, Constant.IS_REMEMBER_ACCOUNT, false);
                        //保存登录状态
                        SpUtil.putBoolean(mContext, Constant.IS_LOGIN, true);
                        //保存登录信息
                        SpUtil.putString(mContext, Constant.TOKEN, data.getToken());
                        SpUtil.putString(mContext, Constant.USER_ACCOUNT, data.getUser_code());
                        SpUtil.putString(mContext, Constant.USER_ACCOUNT_NAME, data.getUser_name());
                        SpUtil.putString(mContext, Constant.USER_PASSWORD, password);
                        SpUtil.putString(mContext, Constant.PAD_SEQ, data.getPADSEQ());

                        //保存权限在本地
                        DBManager.get().loginUserAuthDao().deleteAll();
                        DBManager.get().loginUserAuthDao().insertAll(data.getAUTH());

                    }

                    @Override
                    protected void onFinish() {
                        startActivity(MainActivity.class);
                        finish();
                    }
                });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //将结果转发给EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        requestPermission();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            //从设置页面返回，判断权限是否申请。
            if (EasyPermissions.hasPermissions(this, PERMS)) {
//                ToastUtil.showToast("权限申请成功!");
                goToLogin();
            } else {
                ToastUtil.showToast(getString(R.string.qx_fail));
            }
        }
    }
}
